﻿namespace LiSAClient.Core.Services
{
    using System;
    using System.Runtime.InteropServices;
    using System.Security;
    using GalaSoft.MvvmLight.Messaging;
    using Messages;
    using LiSAService;
    using ServiceProvider;

    public class LoginService : BaseService
    {
        public void Login(string username, SecureString password)
        {
            ServiceHandler.Instance.SetCredentials(
                username,
                this.ConvertToUnsecureString(password)
                );

            UserInfoQueryResult user = null;

            // Calls the service, requesting user information
            ServiceHandler.Instance.WithService(
                svc =>
                {
                    var userQuery = new UserInfoQuery
                    {
                        UserName = username
                    };
                    user = (UserInfoQueryResult)svc.ExecuteQuery(userQuery);
                });

            // If we get here, then the login was successful.
            if (user != null && user.User != null)
            {
                Messenger.Default.Send(new LoginCompletedMessage(user.User));
                return;
            }

            // If we get here, the login failed for some reason.
            Messenger.Default.Send(new LoginFailedMessage());
        }

        /// <summary>
        /// Converts a SecureString from a passwordbox to a regular string
        /// </summary>
        /// <param name="securePassword"></param>
        /// <returns></returns>
        private string ConvertToUnsecureString(SecureString securePassword)
        {
            if (securePassword == null)
            {
                throw new ArgumentNullException("securePassword");
            }

            IntPtr unmanagedString = IntPtr.Zero;
            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
                return Marshal.PtrToStringUni(unmanagedString);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }
    }
}
